﻿using IOA.MES.Business;
using IOA.MES.DataAccess.VModel;
using IOA.MES.TcpApi.Models.Request;
using IOA.MES.TcpApi.Models.Response.SortServer;
using NLog;
using System;
using System.Text;
using System.Web.Http;

namespace IOA.MES.TcpApi.Controllers
{
    /// <summary>
    /// 分拣机服务接口
    /// </summary>
    public class SortServerController : ApiController
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 分拣组件
        /// </summary>
        [HttpPost]
        public ResultJson<PlcHandleResponse> PlcHandle([FromBody] PlcHandleStringRequest request)
        {
            if (request.Data?.Length < 15)
            {
                throw new BizException(1, $"报文长度不合法：{request.Data}");
            }
            var controlChar = request.Data[2];
            var machineNo = request.Data.Substring(4, 5);
            var identify = request.Data[10];
            var barCode = request.Data.Substring(12, request.Data.Length - 12);
            logger.Info($"完整报文：{request.Data}，控制符：{controlChar}，设备编码：{machineNo}，识别状态：{identify}，条码：{barCode}");

            try
            {
                var model = new SortMgr().GetSortRecord(barCode, true);
                if (model == null)
                {
                    logger.Warn($"组件没有分拣记录，条码：{barCode}");
                    return new ResultJson<PlcHandleResponse>(new PlcHandleResponse
                    {
                        Data = $"MKA-ER00000-{barCode}"
                    });
                }

                var stackNo = model.StackNo <= 9 ? model.StackNo.ToString() : (new ASCIIEncoding().GetChars(new byte[] { Convert.ToByte(model.StackNo + 55) })[0]).ToString();
                return new ResultJson<PlcHandleResponse>(new PlcHandleResponse
                {
                    Data = $"MKA-OK{stackNo}{model.SortNo.ToString("00")}{(model.FullCount).ToString("00")}-{model.BarCode}"
                });
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, $"组件分拣异常，条码：{barCode}，异常信息：{ex.Message}");
                return new ResultJson<PlcHandleResponse>(new PlcHandleResponse
                {
                    Data = $"MKA-ER00000-{barCode}"
                });
            }
        }
    }
}
